<?php

namespace app\common\order\model;

use app\common\config\logic\CommonPickerLogic;
use app\common\config\logic\DictionaryLogic;
use app\common\config\model\ConfigStore;
use app\common\config\model\ConfigStorePackage;
use app\common\system\logic\UserLogic;
use think\Model;
use think\model\concern\SoftDelete;

class OrderBom extends Model
{
    use SoftDelete;
    protected $defaultSoftDelete = 0;

    protected $type = [
        'start_time' => 'timestamp',
        'end_time' => 'timestamp',
        'sign_date' => 'timestamp',
        'files' => 'json',
    ];

    public function setFilesAttr($value)
    {
        return empty($value) ? '[]' : json_encode($value);
    }

    public function getFilesAttr($value)
    {
        return empty($value) ? [] : json_decode($value, true);
    }

    public function getStoreAttr($value, $data)
    {
        $dictionaryLogic = new DictionaryLogic();
        $store = $dictionaryLogic->getItem($data['store_id'], ConfigStore::class, ['id', 'title']);

        if (empty($store)) {
            $store = [
                'id' => '',
                'title' => ''
            ];
        }

        return $store;
    }

    public function getPackageAttr($value, $data)
    {
        $model = new ConfigStorePackage();
        $package = $model->where('id', $data['package_id'])->field('id,title,room_type,price')->find();

        if (empty($package)) {
            $package = [
                'id' => '',
                'title' => '',
                'room_type' => '',
                'price' => ''
            ];
        }

        return $package;
    }

    // start_time
    public function getStartTimeAttr($value)
    {
        return empty($value) ? '' : date('Y-m-d', $value);
    }

    // end_time
    public function getEndTimeAttr($value)
    {
        return empty($value) ? '' : date('Y-m-d', $value);
    }

    // sign_date
    public function getSignDateAttr($value)
    {
        return empty($value) ? '' : date('Y-m-d', $value);
    }

    public function getUserAttr($value, $data)
    {
        $logic = new UserLogic();
        $user = $logic->getUser($data['user_id'], ['id', 'realname']);

        if (empty($user)) {
            $user = [
                'id' => '',
                'realname' => ''
            ];
        }

        return $user;
    }
}
